package com.juli.aimanager.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.juli.aimanager.dao.BaseDao;
import com.juli.aimanager.system.service.LoginService;


@Service
public class LoginServiceImpl implements LoginService {
	
	@Resource(name="baseDao")
	private BaseDao baseDao;

	public List loginChecked(Map paramsMap) throws Exception {
		// TODO Auto-generated method stub
		String sql="select user_id ID,username,password   from sys_user where 1=1 [and username='{name}']";
		return baseDao.findAll(sql, paramsMap);
	}

	public List getUserFavorites(String userid) throws Exception {
		// TODO Auto-generated method stub
		String sql = "select uf.userid userid ,uf.menuid menuid , su.* from user_favorite uf , sys_user su where su.userid="+userid;
		return baseDao.findAll(sql);
	}
	
	
	public List getUserRightList(String userid) throws Exception {
		String sql="select sr.permissions from sys_user su ,sys_role sr where sr.roleid=su.roleid and su.userid='"+userid+"' ";
		Map<String, String> map=new HashMap();
		List list=baseDao.findAll(sql,  map);
		String permissions=((HashMap)list.get(0)).get("PERMISSIONS").toString();
		List menuList=getParentList(permissions);
		
		List rightList=new ArrayList();
		for(int i=0;i<menuList.size();i++){
			
			HashMap mapMenu=(HashMap)menuList.get(i);
			if(Integer.parseInt(mapMenu.get("NUMS").toString())>=1){
				mapMenu.put("hasSub", true);
				mapMenu.put("subright", getSubRightList(mapMenu.get("MENUID").toString(),permissions));
			}else{
				mapMenu.put("hasSub", false);
			}
			rightList.add(mapMenu);
			
		}
		return rightList;
	}
	
	public List getParentList(String permissions ) throws Exception{
		String sql_oracle="select t.* ,(select count(1) from sys_menu sm where sm.parentid=t.menuid) nums from sys_menu t where del = '1' and parentid='0' and t.menuid in ('"+permissions.replace(",", "','")+"') order by to_number(orderid) ";
		String sql_mysql="select t.* ,(select count(1) from sys_menu sm where sm.parentid=t.menuid) nums from sys_menu t where del = '1' and parentid='0' and t.menuid in ('"+permissions.replace(",", "','")+"') order by orderid ";
		return baseDao.findAll(sql_mysql,  new HashMap());
	}
	
	public List getSubRightList(String menuid,String permissions) throws Exception{
		String sql="select t.*  "+
				"  from sys_menu t "+
				"  where del = '1' and  t.menuid in ('"+permissions.replace(",", "','")+"') and t.parentid='"+menuid+"' order by orderid ";
		return baseDao.findAll(sql,  new HashMap());
	}
	
	
	
	

}
